class Tag < ActiveRecord::Base
  has_many :taggings, :conditions => ["tag_from IS NOT NULL"], :order => 'taggable_id ASC'
  has_many :issues, :through => :taggings
  #has_many :tester_issues, :through => :taggings, :source => :issue, :conditions => ["taggings.tag_from = ?", "tester"]
  #has_many :system_issues, :through => :taggings, :source => :issue, :conditions => ["taggings.tag_from = ?", "system"]
  #has_many :user_issues, :through => :taggings, :source => :issue, :conditions => ["taggings.tag_from = ?", "user"]
  #has_many :should_test_issues, :through => :taggings, :source => :issue, :conditions => ["taggings.tag_from IN (?)", ["user", "system"]]

  belongs_to :project

  state_machine :state, :initial => :working do
    event :release do
      transition :working => :released
    end
  end

  def self.get_last_released_tag
    all(:conditions => ["state = ?", "released"], :order => "release_at DESC").first
  end

  def on(*taggables)
    taggables.each { |taggable| taggings.create :taggable => taggable, :tag_from => "lable" }
  end

  def on_without_repeat(*taggables)
    @tagged = tagged
    taggables.each { |taggable| taggings.create :taggable => taggable, :tag_from => "lable" unless @tagged.include?(taggable) }
  end

  def update_by_array(*taggables)
    @tagged = tagged
    @deleted = []
    if taggables.empty?
      taggings.delete_all
    else
      taggables.each { |taggable| @deleted << taggable if @tagged.include? taggable }
      @deleted.each { |index| taggables.delete index; @tagged.delete index } unless @deleted.empty?
      @tagged.each { |taggable| taggings.find_all_by_id(taggable.taggings.collect{ |tagging| tagging.id }).each { |item| item.destroy} } unless @tagged.empty?
      taggables.each { |taggable| taggings.create :taggable => taggable, :tag_from => "lable" } unless taggables.empty?
    end
  end

  def tagged
    taggings.collect { |tagging| tagging.taggable }
  end

  def count_tagged
    taggings.count
  end

end
